<?php

namespace app\admin\controller\crm;

use app\common\controller\Backend;
use think\Db;
use think\Session;
use app\admin\model\AuthGroup;
/**
 * 合作记录
 *
 * @icon fa fa-circle-o
 */
class Cooperation extends Backend
{
    
    /**
     * Cooperation模型对象
     * @var \app\admin\model\Cooperation
     */
    protected $model = null;
    protected $admin_data = '';
    protected $admin_group_id = '';
    protected $groupidArray = array();
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Cooperation;
        $adminData = Session::get("admin");
        $linkAdmin = Db::name('Admin');
        if($adminData['id']==7){
            $this->dataLimit = '';
            $this->dataLimitField = '';
        }else{
            $this->dataLimit = 'auth';
            $this->dataLimitField = 'admin_id';
        }
        $this->searchFields = 'id,buser.username';
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name,g.pid')->alias('a')
            ->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();

        //判断当前用户是否是销售部人员
        $linkGroup = Db::name('auth_group');
        $user_verification=false;
        $this->user_verification($this->admin_data['pid'],'销售部',$user_verification);
        if($user_verification){
            //销售部人员
            //查询所有下级销售专员
            $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
            $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();//获取用户权限
            foreach ($groupList as $k=>$v){
                $this->groupidArray[] = $v['id'];
            }
            if($adminData['id']==7){
                //销售助理查询圆总的数据
                $this->groupidArray[] = 2;
            }
            $groupData = array();
            if($this->admin_data['id']==6||$this->admin_data['id']==7){
                //查询所有分组
                $groupData = $linkGroup->where(array('pid'=>15,'status'=>'normal'))->select();
            }else if($this->admin_data['pid']==10||$this->admin_data['pid']==11||$this->admin_data['pid']==12){
                //查询当前分组
                $groupData = $linkGroup->where(array('id'=>$this->admin_data['pid'],'status'=>'normal'))->select();
            }
        }else{
            //查询销售部人员
            $this->di_group(13,$this->groupidArray);
            //查询所有分组
            $groupData = $linkGroup->where(array('pid'=>15,'status'=>'normal'))->select();
        }
        $linkAdmin = Db::name('admin');
        $xiaoData = $linkAdmin->field('a.nickname,a.id')->alias('a')
            ->join('fa_auth_group_access c','a.id = c.uid','LEFT')
            ->where(array('c.group_id'=>array('IN',$this->groupidArray)))->select();
        $this->admin_group_id = $adminData['id'];
        $this->view->assign(array(
            "admin_group_id"=>$this->admin_data['gid'],
            'admin_data'=>$this->admin_data,
            'statusList'=>$this->model->getStatusList(),
            'groupData'=>$groupData,
            'xiaoData'=>$xiaoData
        ));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看网贷客户合作记录
     */
    public function index($ids = '')
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $param = $this->request->param();//判断团队查询
            $param['wf_group_id'] = isset($param['wf_group_id'])?$param['wf_group_id']:'';
            $param['wf_admin_id'] = isset($param['wf_admin_id'])?$param['wf_admin_id']:'';
            $adminWhere = array();
            if($param['wf_admin_id']){
                $adminWhere['admin.id'] = $param['wf_admin_id'];
            }else if($param['wf_group_id']){
                //查询当前组下所有数据
                $groupArray = array();
                $this->di_group($param['wf_group_id'],$groupArray);
                $linkAdmin = Db::name('auth_group_access');
                $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                $adminWhere['admin.id'] = array('IN',$adminIdArray);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['buser','admin','product'])
                    ->where($where)
                    ->where($adminWhere)
                    ->where(array('cooperation.userlist'=>'1'))
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with(['buser','admin','product'])
                    ->where($where)
                    ->where($adminWhere)
                    ->where(array('cooperation.userlist'=>'1'))
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['id','admin_name','myname','mytel','othername','othertel','mode','much','chartimages','cooperationfiles','createtime','endtime','risetime','assessment','evaluate','statuslist','typelist']);
                $row->visible(['buser']);
				$row->getRelation('buser')->visible(['username']);
				$row->visible(['admin']);
				$row->getRelation('admin')->visible(['nickname']);
				$row->visible(['product']);
				$row->getRelation('product')->visible(['product']);
            }
            $list = collection($list)->toArray();
            //查询首签的金额
            $qiData = $this->model->field('SUM(cooperation.much) AS much')->alias('cooperation')
                      ->join('fa_buser buser','buser.id = cooperation.buser_id')
                      ->join('fa_product product','product.id = cooperation.product_id')
                      ->join('fa_admin admin','admin.id = cooperation.admin_id','LEFT')
                      ->where(array('cooperation.typelist'=>'1','cooperation.userlist'=>'1'))
                      ->where($where)
                      ->where($adminWhere)
                      ->select();
            //查询续签金额
            $xuData = $this->model->field('SUM(cooperation.much) AS much')->alias('cooperation')
                        ->join('fa_buser buser','buser.id = cooperation.buser_id')
                        ->join('fa_product product','product.id = cooperation.product_id')
                        ->join('fa_admin admin','admin.id = cooperation.admin_id','LEFT')
                        ->where(array('cooperation.typelist'=>'2','cooperation.userlist'=>'1'))
                        ->where($where)
                        ->where($adminWhere)
                        ->select();
            $shouMoney = ($qiData[0]['much'])?$qiData[0]['much']:0.00;
            $xuMoney = ($xuData[0]['much'])?$xuData[0]['much']:0.00;
            $result = array("total" => $total, "rows" => $list,'shouMoney'=>$shouMoney,'xuMoney'=>$xuMoney);
            return json($result);
        }
        $linkAllot = Db::name('Allot');
        $admin_id = '';
        $allotData = array('admin_id'=>'','username'=>'','product'=>'');
        if($ids){
            $allotData = $linkAllot->field('a.admin_id,b.username,p.product')
                        ->alias('a')->join('fa_buser b','b.id = a.buser_id','LEFT')
                        ->join('fa_product p','p.id = a.product_id','LEFT')
                        ->where(array('a.id'=>$ids,'a.userlist'=>'1'))->find();
            $admin_id = $allotData['admin_id'];
        }
        $this->view->assign('ids',$ids);
        $this->view->assign('admin_id',$admin_id);
        $this->view->assign('allotData',$allotData);
        return $this->view->fetch();
    }

    /**
     * 续约
     * ids:allot表主键ID
     * 适用于所有类型的客户
     */
    public function add($ids=null)
    {
        $allotModel =  new \app\admin\model\Allot();
        $data = $allotModel->field('a.*,b.username,p.product')->alias('a')
                ->join('fa_buser b','b.id = a.buser_id','LEFT')
                ->join('fa_product p','a.product_id = p.id','LEFT')
            ->where(array('a.id'=>$ids,'a.status'=>'6'))->find();
        if(!$data){
            $this->error(__('不存在的续约数据'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $linkAllot = Db::name('Allot');
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['buser_id'] = $data['buser_id'];
                    $params['admin_id'] = $data['admin_id'];
                    $params['product_id'] = $data['product_id'];
                    $params['typelist'] = '2';
                    $params['allot_id'] = $ids;
                    $params['userlist'] = ''.$data['userlist'].'';
                    $params['admin_name'] = $this->admin_data['username'];
                    $result = $this->model->allowField(true)->save($params);
                    $linkAllot->where(array('id'=>$ids))->update(array('qilist'=>'1'));//修改期限状态
                    if ($result !== false) {
                        //把分配数据修改为已备案
                        Db::commit();
                        $this->success();
                    } else {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('data',$data);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //查询客户和产品
        $userData = $this->model->field('b.username,p.product')->alias('c')
                    ->join('fa_buser b','b.id = c.buser_id','LEFT')
                    ->join('fa_product p','c.product_id = p.id','LEFT')
                    ->where(array('c.id'=>$ids))->find();
        $this->view->assign("row", $row);
        $this->view->assign('userData',$userData);
        return $this->view->fetch();
    }
    /**
     * 查询当前客服已经签约的客户
     */
    public function cooperation_buser(){
        if($this->request->isAjax()){
            $admin_id = $this->admin_data['id'];
            $params = $this->request->param();
            $params['username'] = isset($params['username'])?$params['username']:'';
            $params['keyValue'] = isset($params['keyValue'])?$params['keyValue']:'';
            $twoWhere = array('a.status'=>6);
            if($this->admin_data['id']!=1&&$this->admin_data['id']!=2){
                //权限限制
                $twoWhere['a.admin_id'] = $admin_id;
            }
            if($params['keyValue']){
                $twoWhere['a.id'] = $params['keyValue'];
            }
            if($params['username']){
                $twoWhere['b.username'] = array('LIKE','%'.$params['username'].'%');
            }

            $linkAllot = Db::name('Allot');
            $data = $linkAllot->field('a.id,b.username,p.product')->alias('a')
                ->join('fa_buser b','b.id = a.buser_id','LEFT')
                ->join('fa_product p','p.id = a.product_id','LEFT')
                ->where($twoWhere)
                ->select();
            $data = collection($data)->toArray();
            foreach ($data as $k=>$v){
                $name = '客户:"'.$v['username'].'"';
                if($v['product']){
                    $name.=' -  产品:"'.$v['product'].'"';
                }
                $data[$k]['username'] = $name;
            }
            $result = array( "rows" => $data);
            return json($result);
        }
    }

    /**
     * 评价
     */
    public function evaluate($ids=''){
        if(empty($ids)){
            $this->error('操作失败');
        }
        if($this->request->post()){
            //post提交
            $params= $this->request->post('row/a');
            if(empty($params['evaluate'])){
                $this->error(__('请输入评价'));
            }
            $this->model->where(array('id'=>$ids))->update(array('evaluate'=>$params['evaluate']));
            $this->success();
        }
        $data = $this->model->where(array('id'=>$ids))->find();
        if(!$data){
            $this->error('不存在当前数据');
        }
        $this->view->assign('data',$data);
        return $this->fetch();
    }

}
